package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.asl.constant.AslConstant;
import com.ev.common.enums.AuditStatusDict;
import com.ev.custom.dao.ClientDao;
import com.ev.custom.domain.ClientDO;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3ClientSynService;
import com.ev.k3cloudBusiness.vo.K3ClientResultsVO;
import com.ev.k3cloudBusiness.vo.K3DeeSyncVO;
import com.ev.k3cloudBusiness.vo.K3MaterialResultsVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 姚家乐
 * @since 2021/6/1 12:53
 */
@Service
@Slf4j
public class K3ClientSynServiceImpl implements K3ClientSynService {

    @Autowired
    private ClientDao       clientDao;
    @Autowired
    private kingdeeMiddlewareService kingdeeMiddlewareService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R synClient() {
        String clientResult = kingdeeMiddlewareService.CustomerAll();

        K3DeeSyncVO<List<K3ClientResultsVO>> kingdeeSyncVO = new Gson().fromJson(clientResult,new TypeToken<K3DeeSyncVO<List<K3ClientResultsVO>>>(){}.getType());
        if(!AslConstant.ZERO.equals(kingdeeSyncVO.getCode()))
        {
            log.info(kingdeeSyncVO.getMsg());
            return  R.error(kingdeeSyncVO.getMsg());
        }
        List<K3ClientResultsVO> k3ClientResultsVOS = kingdeeSyncVO.getData();

        Map<String, Object> param = Maps.newHashMap();
        List<ClientDO> clientDOS = clientDao.list(param);
        // 现存的客户ID
        List<Long> localIdList = clientDOS.stream().map(ClientDO::getId)
            .collect(Collectors.toList());
        // remote
        List<Long> remoteIdList = k3ClientResultsVOS.stream().map(K3ClientResultsVO::getId)
            .collect(Collectors.toList());
        // 已被删除或禁用的(本地库有，远端库没的)
        List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e))
            .collect(Collectors.toList());
        // 修改的（本地库有的，远端库有的）
        List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains)
            .collect(Collectors.toList());
        // 新增的（本地库无的，远端库有的）
        remoteIdList.removeAll(updateIdList);

        long okAudit = AuditStatusDict.OK_AUDIT.getId();
        Long userId = ShiroUtils.getUserId();
        ClientDO clientDO;

        List<ClientDO> updateClientDOList = Lists.newArrayList();
        if (deleteIdList.size() > 0) {
            List<ClientDO> updateList = clientDOS.stream()
                .filter(e -> deleteIdList.contains(e.getId())).collect(Collectors.toList());
            for (ClientDO client:
            updateList) {
                client.setUseStatus(0);
                client.setDelFlag(1);
            }
            updateList.forEach(e -> e.setUseStatus(0));
            updateClientDOList.addAll(updateList);
        }
        if (updateIdList.size() > 0) {
            List<K3ClientResultsVO> updateList = k3ClientResultsVOS.stream()
                .filter(e -> updateIdList.contains(e.getId())).collect(Collectors.toList());
            List<ClientDO> updateClientList = Lists.newArrayList();
            for (K3ClientResultsVO kingdeeClientSyncVO : updateList) {
                clientDO = new ClientDO();
                clientDO.setId(kingdeeClientSyncVO.getId());
                clientDO.setCode(kingdeeClientSyncVO.getNumber());
                clientDO.setAddress(kingdeeClientSyncVO.getAddress());
                clientDO.setName(kingdeeClientSyncVO.getName());
                updateClientList.add(clientDO);
            }
            updateClientDOList.addAll(updateClientList);
        }
        if (updateClientDOList.size() > 0) {
            log.info("批量修改");
        }

        if (remoteIdList.size() > 0) {
            List<K3ClientResultsVO> saveList = k3ClientResultsVOS.stream()
                .filter(e -> remoteIdList.contains(e.getId())).collect(Collectors.toList());
            List<ClientDO> saveClientDOList = Lists.newArrayList();
            for (K3ClientResultsVO kingdeeClientSyncVO : saveList) {
                clientDO = new ClientDO();
                clientDO.setStatus(okAudit);
                clientDO.setAuditId(userId);
                clientDO.setUseStatus(1);
                clientDO.setId(kingdeeClientSyncVO.getId());
                clientDO.setCode(kingdeeClientSyncVO.getNumber());
                clientDO.setAddress(kingdeeClientSyncVO.getAddress());
                clientDO.setName(kingdeeClientSyncVO.getName());
                saveClientDOList.add(clientDO);
            }
            log.info("批量保存");
            clientDao.batchSave(saveClientDOList);
        }
        return R.ok();
    }
}
